package myJs

import myJs.myPkg.bootstrap.Bootstrap.default._
import myJs.Tool.{layerOptions, myElement}
import myJs.Utils._
import myJs.myPkg.{ColumnOptions, Swal, SwalOptions, TableOptions}
import scalatags.Text.{TypedTag, all}
import scalatags.Text.all._

import scala.scalajs.js
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import myJs.Implicits._
import org.scalajs.dom.FormData
import org.scalajs.dom.ext.Ajax
import myJs.myPkg.jquery._
import org.scalajs.dom._
import shared.VarTool

import scala.concurrent.Await
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.Duration
import async.Async._
import scala.collection.immutable.SeqMap
import scala.scalajs.js.Dynamic.{global => g}
import scala.scalajs.js.JSConverters._

/**
 * Created by yz on 2019/4/25
 */
@JSExportTopLevel("ConfigManage")
object ConfigManage {

  @JSExport("init")
  def init = {

    addButtonShow

    initTable
    refreshConfig { () =>

    }

    bootStrapValidator

  }

  def tbFmt(columnName: String): js.Function = (v: js.Any, row: js.Dictionary[js.Any]) => columnName match {
    case _ => v
  }

  def expStyle(columnName: String): js.Function = (v: js.Any, row: js.Dictionary[Any]) => columnName match {
    case _ => v
  }

  val operateColumn = js.Array(
    ColumnOptions.field("operate").title("操作").formatter(operateFmt).filterControl("clear")
  )

  def initTable = {
    val map = SeqMap("name" -> "名称", "createTime" -> "创建时间")
    val columnNames = map.keyList
    val columns = columnNames.map { columnName =>
      val title = map.getOrElse(columnName, columnName)
      val fmt = tbFmt(columnName)
      val style = expStyle(columnName)
      val basicOptions = ColumnOptions.field(columnName).title(title).sortable(true).formatter(fmt).cellStyle(style)
      columnName match {
        case x if List().contains(x) => basicOptions.
          sortable(false).operateable(true)
        case _ => basicOptions
      }
    }.concat(operateColumn)
    val options = TableOptions.columns(columns.toJSArray).searchOnButton(false).filterControl(false)
    $(s"#table").bootstrapTable(options)
  }

  def getIsMet={
    g.isMet.toB
  }

  @JSExport("refreshConfig")
  def refreshConfig(f: () => Any = () => ()) = {
    val url = g.jsRoutes.controllers.ConfigController.getAll().url.toString
    val ajaxSettings = JQueryAjaxSettings.url(s"${url}?").contentType("application/json").
      `type`("get").success { (data, status, e) =>
      $("#table").bootstrapTable("load", data)
      f()
    }
    $.ajax(ajaxSettings)
  }

  @JSExport("addShow")
  def addShow = {
    jQuery("#addModal").modal("show")
  }

  def addButtonShow = {
    if (getIsMet) {
      $("#addConfigButton").show()
    } else $("#addConfigButton").hide()
  }

  def operateFmt: js.Function = {
    (v: js.Any, row: js.Dictionary[js.Any]) =>
      val useConfigUrl = g.jsRoutes.controllers.MissionController.newMissionBefore().url.toString
      val useConfigStr = a(title := "使用", href := s"${useConfigUrl}?id=${row("id")}", cursor.pointer,
        span(em(cls := "fa fa-repeat"))
      )
      val deleteStr = a(title := "删除", onclick := s"ConfigManage.delete('${row("id")}')", cursor.pointer,
        span(em(cls := "fa fa-close"))
      )

      val downloadStr = if (getIsMet) {
        val downloadUrl = g.jsRoutes.controllers.ConfigController.downloadConfig().url.toString
        a(title := "导出方案", href := s"${downloadUrl}?id=${row("id")}", cursor.pointer,
          span(em(cls := "fa fa-download"))
        )
      } else span()
      List(useConfigStr, downloadStr, deleteStr).mkString("&nbsp;")
  }

  @JSExport("add")
  def add = {
    val bv = jQuery("#form").data("bootstrapValidator")
    bv.validate()
    val valid = bv.isValid().toB
    if (valid) {
      val data = $(s"#form").serialize()
      val index = layer.alert(myElement, layerOptions)
      val url = g.jsRoutes.controllers.ConfigController.addByFile().url.toString
      val formData = new FormData(document.getElementById("form").toHTMLFormElement)
      Ajax.post(url = s"${url}", data = formData,
        responseType = "application/json").map { xhr =>
        val json = xhr.response.toJDS
        refreshConfig { () =>
          layer.close(index)
          jQuery("#addModal").modal("hide")
          bv.resetForm(true)
          Swal.swal(SwalOptions.title("成功").text("新增成功!").`type`("success"))
        }
      }
    }
  }

  @JSExport("delete")
  def delete(id: String) = {
    val options = SwalOptions.title("").text("确定要删除此数据吗？").`type`("warning").showCancelButton(true).
      showConfirmButton(true).confirmButtonClass("btn-danger").confirmButtonText("确定").closeOnConfirm(false).
      cancelButtonText("取消").showLoaderOnConfirm(true)
    Swal.swal(options, () => {
      val url = g.jsRoutes.controllers.ConfigController.deleteById().url.toString
      val ajaxSettings = JQueryAjaxSettings.url(s"${url}?id=${id}").
        `type`("get").contentType("application/json").success { (data, status, e) =>
        refreshConfig { () =>
          Swal.swal(SwalOptions.title("成功").text("删除成功").`type`("success"))
        }
      }.error { (data, status, e) =>
        Swal.swal(SwalOptions.title("错误").text("删除失败").`type`("error"))
      }
      $.ajax(ajaxSettings)

    })
  }

  def bootStrapValidator = {
    val url = g.jsRoutes.controllers.ConfigController.nameCheck().url.toString
    val dict = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> js.Dictionary(
        "configName" -> js.Dictionary(
          "validators" -> js.Dictionary(
            "notEmpty" -> js.Dictionary(
              "message" -> "参数方案名不能为空！"
            ),
            "remote" -> js.Dictionary(
              "message" -> "参数方案名已存在！",
              "url" -> url,
              "delay" -> 1000,
              "type" -> "POST",
            ),
          )
        ),
        "file" -> js.Dictionary(
          "validators" -> js.Dictionary(
            "notEmpty" -> js.Dictionary(
              "message" -> "请选择一个参数方案文件!"
            ),
            "file" -> js.Dictionary(
              "message" -> "请选择一个(*.mcfg)格式的参数方案文件!",
              "extension" -> "mcfg",
            ),
          )
        ),
      )
    )
    g.$("#form").bootstrapValidator(dict)

  }


}
